<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;
use app\common\controller\Api;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\service\AddService;
use app\common\service\OrdinaryService;
use app\web\controller\Express;
use think\Db;
use think\Validate;


/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Order extends Auth
{
    public $noNeedLogin = [];
    /**
     * 添加订单
     */
    public function add(){
        if($this->request->isPost()){
            $userInfo = $this->userInfo;
            $getData= $this->request->post();
            $validate = new \app\web\validate\Order();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            if(!isset($getData['man_num'])){$getData['man_num'] = 0;}
            if(!isset($getData['woman_num'])){$getData['woman_num'] = 0;}
            if(!isset($getData['other_num'])){$getData['other_num'] = 0;}
            $totalNum = $getData['man_num'] + $getData['woman_num'] + $getData['other_num'];
            if( $getData['order_type'] == '1' && $totalNum <= 0){
                $this->result('请至少选择一个技师', '', 204);
            }
            if(empty($getData['hand_card_id'])){
                $getData['hand_card_id'] = '0';
            }
            //延迟时间为0
            if(empty($getData['delay'])){
                $getData['delay'] = 0;
            }
            //默认立刻排钟
            if( empty($getData['time_type'])){
                $getData['time_type'] = 1;
            }
            $projectName = Db::name('qt_project')->where('id',$getData['project_id'])->value('name');
            $getData['create_id'] = $userInfo['id'];
            //不自动排钟
            if(($getData['order_type'] == '1' && $this->storeInfo['is_auto_queue'] == '0') || $getData['time_type'] == '2'){
                if( empty($getData['man_num'])){
                    $getData['man_num'] = 0;
                }else{
                    $sex = '1';
                    $number = $getData['man_num'];
                    $this->wait($getData,$this->storeInfo,$projectName,$sex,$number,$this->userInfo);
                }
                if( empty($getData['woman_num'])){
                    $getData['woman_num'] = 0;
                }else{
                    $sex = '2';
                    $number = $getData['woman_num'];
                    $this->wait($getData,$this->storeInfo,$projectName,$sex,$number,$this->userInfo);
                }
                if( empty($getData['other_num'])){
                    $getData['other_num'] = 0;
                }else{
                    $sex = '3';
                    $number = $getData['other_num'];
                    $this->wait($getData,$this->storeInfo,$projectName,$sex,$number,$this->userInfo);
                }
                $this->result('添加成功', '', 200);
            }
            //房间床位数限制
            $roomNumber = Db::name('qt_room')->where(['id'=>$getData['room_id']])->value('bed_num');
            $roomUseOrder = Db::name('qt_order')->where(['room_id'=>$getData['room_id'],'pay_status'=>'1'])->find();
            $usedNumber = 0;
            $totalNum = $getData['man_num'] + $getData['woman_num'] + $getData['other_num'];
            if(!empty($roomUseOrder)){
                $usedNumber = Db::name('qt_order_project')
                    ->whereNotNull('engineer_id')
                    ->where(['order_id'=>$roomUseOrder['id'],'is_change'=>'1','is_add'=>'1'])
                    ->where('status','<','3')
                    ->where('is_delete',2)
                    ->count();
            }
            if($getData['order_type'] == '1'){
                //判断当前房间内未结账的项目数
                if(($usedNumber + $totalNum) > $roomNumber){
                    $this->result('超出房间床位数','',204);
                }
            }else{
                if(($usedNumber + 1) > $roomNumber ){
                    $this->result('超出房间床位数','',204);
                }
            }
            $getData['creater_room'] = Db::name('qt_room_log')
                ->where(['room_id'=>$getData['room_id']])
                ->order('id desc')
                ->value('user_id');
            if ($this->storeInfo['floor_commission_type'] == '1') {
                $getData['sale_id'] = $userInfo['id'];
            } else {
                $getData['sale_id'] = $getData['creater_room'];
            }
            $orderModel = new \app\common\model\Order();
            $code = $orderModel->create_order($getData,$userInfo);
            if($code['code'] == '200'){
                Db::name('qt_room')->where(['id'=>$getData['room_id']])->update(['retreat_time'=>null]);
                $this->result('下单成功','',200);
            }
        }else{
            $this->result('无效的请求','',204);
        }

    }


    /**
     * 订单派技师
     * @param $order[订单信息]
     * @param $type [订单类型]
     */
    public function scheduling($order,$type){
        //获取可做项目的所有空闲技师
        $userIds = Db::name('qt_user_project')
            ->alias('up')
            ->leftJoin('qt_users u','u.id = up.engineer_id')
            ->where('up.project_id',$order['project_id'])
            ->where('u.work_status','1')
            ->group('up.engineer_id')
            ->column('up.engineer_id');
        if($type == '1'){
            //查找今日未排班的技师
            $sort = Db::name('qt_scheduling_queue')
                ->whereIn('engineer_id',$userIds)
                ->where(['current'=>'1'])
                ->order('sort asc')
                ->find();
            //如果有的话排技师，直接排技师
            if(!empty($sort)){
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_order_project')->where(['id'=>$order['id']])->update(['engineer_id'=>$sort['engineer_id']]);
                    //更新技师状态
                    Db::name('qt_users')->where('id',$sort['engineer_id'])->update(['work_status'=>'5']);
                    //更新默认排序
                    Db::name('qt_scheduling_queue')->where('engineer_id',$sort['engineer_id'])->update(['current'=>'2']);
                    //上钟表中加数据
                    $orderQueue['store_id'] = $order['store_id'];
                    $orderQueue['user_id'] = $sort['engineer_id'];
                    $orderQueue['room_id'] = $order['room_id'];
                    $orderQueue['project_id'] = $order['project_id'];
                    $orderQueue['order_project_id'] = $order['order_id'];
                    $orderQueue['order_user_id'] = $order['created_order_id'];
                    $sort = Db::name('qt_order_queue')->where('day',date("Y-m-d"))->order('sort desc')->find();
                    $orderQueue['sort'] = $sort['sort'] + 1;
                    $orderQueue['day'] = date("Y-m-d");
                    $orderQueue['type_id'] = $sort['type_id'];
                    $orderQueue['status'] = '2';
                    $orderQueue['created_time'] = time();
                    Db::name('qt_order_queue')->insert($orderQueue);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('排班失败','',204);
                }
            }else{
                //在已经上钟的队列里面找到空闲的进行排技师
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_order_project')->where(['id'=>$order['id']])->update(['engineer_id'=>$sort['engineer_id']]);
                    //更新技师状态
                    Db::name('qt_users')->where('id',$sort['engineer_id'])->update(['work_status'=>'5']);
                    //查找上钟表中空闲的技师
                    $userRes = Db::name('qt_order_queue')
                        ->whereIn('user_id',$userIds)
                        ->where(['status'=>'1'])
                        ->where('day',date('Y-m-d'))
                        ->order('sort asc')
                        ->find();
                    //查找最大的排序
                    $sort = Db::name('qt_order_queue')
                        ->whereIn('user_id',$userIds)
                        ->where(['status'=>'1'])
                        ->where('day',date('Y-m-d'))
                        ->order('sort desc')
                        ->find();
                    //更新符合条件的技师信息
                    Db::name('qt_order_queue')
                        ->where('user_id',$userRes['user_id'])
                        ->where('day',date('Y-m-d'))
                        ->update([
                            'sort'=>$sort['sort'] + 1,
                            'room_id'=>$order['room_id'],
                            'project_id'=>$order['project_id'],
                            'order_project_id'=>$order['order_id'],
                            'status'=>'2'
                        ]);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('排班失败','',204);
                }
            }
        }else{
            //在已经上钟的队列里面找到空闲的进行排技师
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_order_project')->where(['id'=>$order['id']])->update(['engineer_id'=>$order['engineer_id']]);
                //更新技师状态
                Db::name('qt_users')->where('id',$order['engineer_id'])->update(['work_status'=>'5']);
                //查找最大的排序
                $sort = Db::name('qt_order_queue')
                    ->whereIn('user_id',$userIds)
                    ->where(['status'=>'1'])
                    ->where('day',date('Y-m-d'))
                    ->order('sort desc')
                    ->find();
                //更新符合条件的技师信息
                $engineerRes = Db::name('qt_order_queue')->where('user_id',$order['engineer_id'])->find();
                if($engineerRes['status'] != '1'){
                    $this->result('该技师未处于空闲状态','',204);
                }
                Db::name('qt_order_queue')
                    ->where('user_id',$order['engineer_id'])
                    ->where('day',date('Y-m-d'))
                    ->update([
                        'sort'=>$sort['sort'] + 1,
                        'room_id'=>$order['room_id'],
                        'project_id'=>$order['project_id'],
                        'order_project_id'=>$order['order_id'],
                        'status'=>'2'
                    ]);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('排班失败','',204);
            }
        }
    }



    /**
     * 单据查询
     */
    public function bill(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $where = 1;
            //房间号
            if(isset($getData['room_id']) && !empty($getData['room_id'])){
                $where['cl.room_id'] = $getData['room_id'];
            }
            //技师号
            if(isset($getData['cashier_id'])&& !empty($getData['cashier_id'])){
                $where['c.cashier_id'] = $getData['cashier_id'];
            }
            //订单号
            if(isset($getData['order_no']) &&!empty($getData['order_no'])){
                $where['o.order_no'] = $getData['order_no'];
            }
            //订单状态
            if(isset($getData['is_pay'])&& !empty($getData['is_pay'])){
                $where['cl.is_pay'] = $getData['is_pay'];
            }
            $sql  = Db::name('qt_commission_log')
                ->alias('cl')
                ->leftJoin('qt_order o','o.id = cl.product_id')
                ->leftJoin('qt_room r','o.room_id = r.id')
                ->leftJoin('qt_order_project op','op.order_id = o.id')
                ->field('cl.id,o.order_no,cl.money,cl.is_pay,cl.updated_time,o.pay_status,r.name,op.name,op.order_type,op.is_add,op.num,op.engineer_id')
                ->where($where)
                ->where('cl.type','1');
            if(isset($getData['start_time'])){
                $sql->whereTime('cl.updated_time',$getData['start_time'],$getData['end_time']);
            }
            $data = $sql->paginate($getData['limit'])->each(function ($item){
                $engineerNumber = Db::name('qt_users')->where('id',$item['engineer_id'])->value('work_number');
                $item['engineer_number'] = $engineerNumber;
                return $item;
            });
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }



    /**
     * 单据查询
     */
    public function order_bill(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $where = 1;
            //房间号
            if(isset($getData['room_id'])){
                $where['cl.room_id'] = $getData['room_id'];
            }
            //下单人
            if(isset($getData['user_id'])){
                $where['cl.user_id'] = $getData['user_id'];
            }
            //项目ID
            if(isset($getData['product_id'])){
                $where['cl.product_id'] = $getData['product_id'];
            }

            //技师号
            if(isset($getData['cashier_id'])){
                $where['ccashier_id'] = $getData['cashier_id'];
            }
            //订单号
            if(isset($getData['order_no'])){
                $where['o.order_no'] = $getData['order_no'];
            }
            //订单状态
            if(isset($getData['is_pay'])){
                $where['cl.is_pay'] = $getData['is_pay'];
            }
            $sql  = Db::name('qt_commission_log')
                ->alias('cl')
                ->leftJoin('qt_order o','o.id = cl.product_id')
                ->leftJoin('qt_room r','o.room_id = r.id')
                ->field('cl.id,o.order_no,cl.money,cl.is_pay,cl.updated_time,o.pay_status,r.name')
                ->where($where)
                ->where('cl.type','1');
            if(isset($getData['start_time'])){
                $sql->whereTime('cl.updated_time',$getData['start_time'],$getData['end_time']);
            }
            $data = $sql->paginate($getData['limit']);
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }



    /**
     * 充值查询
     */
    public function recharge_bill(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $where = 1;
            //手机号
            if(isset($getData['phone'])){
                $where['c.phone'] = $getData['phone'];
            }
            //卡号
            if(isset($getData['card_no'])){
                $where['c.card_no'] = $getData['card_no'];
            }
            //卡类型
            if(isset($getData['viper_type_id'])){
                $where['c.viper_type_id'] = $getData['viper_type_id'];
            }
            //充值模板
            if(isset($getData['recharge_tempid'])){
                $where['rl.recharge_tempid'] = $getData['recharge_tempid'];
            }

            //付款方式
            if(isset($getData['pay_type'])){
                $where['rl.pay_type'] = $getData['pay_type'];
            }

            //销售类型:1=楼面,2=技师
            if(isset($getData['type'])){
                $where['c.type'] = $getData['type'];
            }

            //销售人
            if(isset($getData['saler_id'])){
                $where['c.saler_id'] = $getData['saler_id'];
            }

            //订单状态
            if(isset($getData['pay_status'])){
                $where['rl.pay_status'] = $getData['pay_status'];
            }
            $sql  = Db::name('qt_viper_card_recharge_log')
                ->alias('rl')
                ->leftJoin('qt_viper_card c','c.id = rl.viper_card_id')
                ->field('rl.id,rl.order_no,rl.amount,rl.pay_status,rl.pay_time')
                ->where($where);
            if(isset($getData['start_time'])){
                $sql->whereTime('rl.pay_time',$getData['start_time'],$getData['end_time']);
            }
            $data = $sql->paginate($getData['limit']);
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }




    /**
     * 月卡次卡查询
     */
    public function moth_bill(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $where = 1;
            //手机号
            if(isset($getData['phone'])){
                $where['c.phone'] = $getData['phone'];
            }
            //卡号
            if(isset($getData['card_no'])){
                $where['c.card_no'] = $getData['card_no'];
            }
            //卡类型
            if(isset($getData['viper_type_id'])){
                $where['c.viper_type_id'] = $getData['viper_type_id'];
            }
            //充值模板
            if(isset($getData['recharge_tempid'])){
                $where['rl.recharge_tempid'] = $getData['recharge_tempid'];
            }

            //付款方式
            if(isset($getData['pay_type'])){
                $where['rl.pay_type'] = $getData['pay_type'];
            }

            //销售类型:1=楼面,2=技师
            if(isset($getData['type'])){
                $where['c.type'] = $getData['type'];
            }

            //销售人
            if(isset($getData['saler_id'])){
                $where['c.saler_id'] = $getData['saler_id'];
            }

            //订单状态
            if(isset($getData['pay_status'])){
                $where['rl.pay_status'] = $getData['pay_status'];
            }
            $sql  = Db::name('qt_viper_card_recharge_log')
                ->alias('rl')
                ->leftJoin('qt_viper_card c','c.id = rl.viper_card_id')
                ->field('rl.id,rl.order_no,rl.amount,rl.pay_status,rl.pay_time')
                ->where($where);
            if(isset($getData['start_time'])){
                $sql->whereTime('rl.pay_time',$getData['start_time'],$getData['end_time']);
            }
            $data = $sql->paginate($getData['limit']);
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 获取房间等待列表
     */
    public function waitList(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $where = [];
            //房间筛选
            if(!empty($getData['room_id'])){
                $where[] =  ['ro.room_id','=',$getData['room_id']];
            }
            //数量筛选
            if(!empty($getData['number'])){
                $where[] =  ['ro.number','=',$getData['number']];
            }

            //性别筛选
            if(!empty($getData['sex'])){
                $where[] =  ['ro.sex','=',$getData['sex']];
            }
            //项目筛选
            if(!empty($getData['project_id'])){
                $where[] =  ['ro.project_id','=',$getData['project_id']];
            }
            $data = Db::name('qt_wait')
                ->field('ro.*,u.real_name,r.name as room_name,p.name as project_name')
                ->alias('ro')
                ->leftJoin('qt_users u','u.id = ro.create_id')
                ->leftJoin('qt_room r','r.id = ro.room_id')
                ->leftJoin('qt_project p','ro.project_id = p.id')
                ->where(['ro.store_id'=>$this->userInfo['store_id'],'ro.status'=>'1','ro.delay_time'=>'0'])
                ->where('ro.number','>','0')
                ->where($where)
                ->select();
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 安排技师
     */
    public function arrange(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            if(empty($getData['id']) || empty($getData['engineer_ids'])){
                $this->result('缺少参数','',204);
            }
            $waitRes = Db::name('qt_wait')->where('id',$getData['id'])->find();
            if (!empty($waitRes)) {
                //查找可以安排的技师
                $data['man_num'] = 0;
                $data['woman_num'] = 0;
                $data['other_num'] = 0;
                if($waitRes['sex'] == '1'){
                    $data['man_num'] = $waitRes['number'];
                }
                if($waitRes['sex'] == '2'){
                    $data['woman_num'] = $waitRes['number'];
                }
                if($waitRes['sex'] == '3'){
                    $data['other_num'] = $waitRes['number'];
                }
                $data['project_id'] = $waitRes['project_id'];
                $data['room_id'] = $waitRes['room_id'];
                $data['hand_card_id'] = '';
                $data['delay']= 0;
                $data['time_type'] = 1;
                $data['order_type'] = 4;
                $data['create_id'] = $userInfo['id']?? '';
                $data['engineer_id'] = $getData['engineer_ids'];
                $data['creater_room'] = Db::name('qt_room_log')->where(['room_id'=>$waitRes['room_id']])->order('id desc')->value('user_id');
                $data['sale_id'] = $userInfo['id']?? '';
                $orderModel = new \app\common\model\Order();
                $code = $orderModel->create_order($data,$userInfo);
                if($code['code'] == '200'){
                    Db::name('qt_wait')->where(['id' => $waitRes['id']])->update(['status' => '2']);
                }$this->result('下单成功','',200);
            }else{
                $this->result('安排失败','',204);
            }
        }else{
            $this->result('无效的请求','',204);
        }

    }

    /**
     * 添加等位或者延迟排钟
     * @param $getData
     * @param $storeInfo
     * @param $projectName
     * @param $sex
     * @param $number
     * @param $userInfo
     */
    public  function wait($getData,$storeInfo,$projectName,$sex,$number,$userInfo){
        if($getData['order_type'] == '1' && $storeInfo['is_auto_queue'] == '0'){
            $roomOrder = [
                'store_id'=>$this->userInfo['store_id'],
                'room_id'=>$getData['room_id'],
                'project_id'=>$getData['project_id'],
                'project_name'=>$projectName,
                'sex'=>$sex,
                'number'=>$number,
                'create_id'=>$userInfo['id'],
                'create_time'=>time(),
            ];
            Db::name('qt_wait')->insert($roomOrder);
            return true;
        }
        //延时排钟记录
        if($getData['time_type'] == '2'){
            if(empty($getData['delay'])){
                $this->result('缺少延时排钟时间','',200);
            }
            $roomOrder = [
                'store_id'=>$this->userInfo['store_id'],
                'room_id'=>$getData['room_id'],
                'project_id'=>$getData['project_id'],
                'project_name'=>$projectName,
                'sex'=>$sex,
                'number'=>$number,
                'create_id'=>$userInfo['id'],
                'delay_time'=>$getData['delay'],
                'create_time'=>time(),
            ];
            Db::name('qt_wait')->insert($roomOrder);
            return true;
        }
        return false;
    }


}
